﻿#include "listview.h"
#include "ui_listview.h"
#include <QHBoxLayout>
#include <QPushButton>
#include <QtDebug>
#include <QGraphicsOpacityEffect>
#include "customlistitem.h"
#include "jsonutils.h"
#include "itemmodel.h"
#include "cmaskwidget.h"

ListView::ListView(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ListView)
{
    ui->setupUi(this);

    // 实验：代码方式增加图标
    this->addIcon();

    // 实验：增加整体透明
//    this->setOpacity();


    this->loadL1();
    this->loadL2();
    this->loadL3();

    this->activeTreeBox(2);

    // 创建遮罩控件
    maskWidget = CMaskWidget::GetInstance();
    maskWidget->setParent(this);
    maskWidget->SetMainWidget(this);
    maskWidget->hide();


    // 激活键盘事件获取
    this->grabKeyboard();

    this->popupTree = nullptr;
}

ListView::~ListView()
{
    delete ui;
}

void ListView::addIcon()
{


    //            fac.buildIcoBtn(this, ":/Login/tipIcon.png");


    QPixmap *pixmap = NULL;
    pixmap = new QPixmap(42, 38);
    pixmap->load(":/res/actions-title-icon.png");
    QIcon *icon = new QIcon(*pixmap);

    QPushButton * pbtnIco = new QPushButton(*icon,"");

    QImage img(":/res/actions-title-icon.png");
    pbtnIco->setFixedSize(img.size());
    QSize size;
    size.setWidth(22);
    size.setHeight(18);
    pbtnIco->setIconSize(size);
    pbtnIco->setStyleSheet("background: transparent;border:none;");


    qDebug() << img.width() << img.height() << endl;


    QHBoxLayout * pLay = new QHBoxLayout();
    pLay->setContentsMargins(0,0,0,0);
    pLay->addSpacing(25);
    pLay->addWidget(pbtnIco);
    pLay->addStretch(0);
    this->ui->label->setLayout(pLay);
    this->ui->label->setContentsMargins(0,10,10,10);

//        this->ui->label->setFixedSize(270,38);
    this->ui->label->show();

    //        this->ui->label->setStyleSheet("color:#cc0000;background-color:#fff9ef;border-width: 1px;border-style: solid;border-color: #ff5b5b;");


}

void ListView::setOpacity()
{
    QGraphicsOpacityEffect *opacityEffect=new QGraphicsOpacityEffect;
    ui->styleItemBox->setGraphicsEffect(opacityEffect);
    opacityEffect->setOpacity(0.7);
}

void ListView::loadL1()
{
    // 定义盒子
    QVBoxLayout* layout = new QVBoxLayout();

    // 读取树结构信息
    QString filePath = QCoreApplication::applicationDirPath() + "/tree.json";
    QList<ItemModel> items;
    JsonUtils::readJsonFile(filePath, true, items);
    CustomListItem* item;
    for (int i = 0;i < items.size();i++) {
        ItemModel itemModel = items.at(i);
        item = new CustomListItem(itemModel);

        // 有点浪费效率，但还是先添加上吧(理论上应该加入到父组件上，但是父组件不是自己定义的，所以将就用)
        connect(item,  &CustomListItem::clicked, [=](){
            this->activeTreeBox(0);
        });


        layout->addWidget(item);
        if (i == 0) {
            item->selected();
        }
    }
    qDebug() << "根节点数据量," << items.size() << endl;
    layout->setAlignment(Qt::AlignTop);
    layout->setMargin(0);
    layout->setSpacing(0);
    layout->setContentsMargins(0,30,0,0);
    this->ui->styleItemBox->setLayout(layout);

}

void ListView::loadL2()
{
    // 找到当前选择的一级ID
    QList<CustomListItem*> _items = this->ui->styleItemBox->findChildren<CustomListItem *>();
    CustomListItem *item=NULL;
    QString rootId;
    for(auto it=_items.begin();it!=_items.end();it++)
    {
        item=*it;
        if (item->isSelected()) {
            // 查到选中的ID
            rootId = item->getKey();
            break;
        }
    };


    // 定义盒子
    QVBoxLayout* layout = new QVBoxLayout();

    // 读取树结构信息
    QString filePath = QCoreApplication::applicationDirPath() + "/tree.json";
    QList<ItemModel> items;
    JsonUtils::readJsonFile(filePath, false, items);
    bool firstSelect = false;
    for (int i = 0; i < items.size(); i++) {
        ItemModel itemModel = items.at(i);
        if (itemModel.parentId == rootId) {
            item = new CustomListItem(itemModel);
            // 有点浪费效率，但还是先添加上吧(理论上应该加入到父组件上，但是父组件不是自己定义的，所以将就用)
            connect(item,  &CustomListItem::clicked, [=](){
                this->activeTreeBox(1);
            });
            layout->addWidget(item);
            if (!firstSelect) {
                item->selected();
                firstSelect = true;
            }
        }
    }
    layout->setAlignment(Qt::AlignTop);
    layout->setMargin(0);
    layout->setSpacing(0);
    layout->setContentsMargins(0,30,0,0);
    this->ui->actionItemBox->setLayout(layout);

}

void ListView::loadL3()
{
    // 找到当前选择的二级ID
    QList<CustomListItem*> _items = this->ui->actionItemBox->findChildren<CustomListItem *>();
    CustomListItem *item=NULL;
    QString parentId;
    for(auto it=_items.begin();it!=_items.end();it++)
    {
        item=*it;
        if (item->isSelected()) {
            // 查到选中的ID
            parentId = item->getKey();
            break;
        }
    };

    // 定义盒子
    QVBoxLayout* layout = new QVBoxLayout();

    // 读取树结构信息
    QString filePath = QCoreApplication::applicationDirPath() + "/tree.json";
    QList<ItemModel> items;
    JsonUtils::readJsonFile(filePath, false, items);
    bool firstSelect = false;
    for (int i = 0; i < items.size(); i++) {
        ItemModel itemModel = items.at(i);
        if (itemModel.parentId == parentId) {
            item = new CustomListItem(itemModel, CustomListItem::ItemStyle::PairIcon);
            // 有点浪费效率，但还是先添加上吧(理论上应该加入到父组件上，但是父组件不是自己定义的，所以将就用)
            connect(item,  &CustomListItem::clicked, [=](){
                this->activeTreeBox(2);
            });
            layout->addWidget(item);
            if (!firstSelect) {
                item->selected();
                firstSelect = true;
            }
        }
    }
    layout->setAlignment(Qt::AlignTop);
    layout->setMargin(0);
    layout->setSpacing(0);
    layout->setContentsMargins(0,30,0,0);
//    this->ui->skill->setLayout(layout);
    this->ui->skillItemBox->setLayout(layout);
}

void ListView::activeTreeBox(int i)
{
    this->setOpacity(*this->ui->styleBox, 0.5);
    this->setOpacity(*this->ui->actionBox, 0.5);
    this->setOpacity(*this->ui->skillBox, 0.5);
    switch (i) {
        case 0:
            this->setOpacity(*this->ui->styleBox, 1);
            break;
        case 1:
            this->setOpacity(*this->ui->actionBox, 1);
            break;
        case 2:
            this->setOpacity(*this->ui->skillBox, 1);
            break;
    }
    this->crtSelBox = i;
}

void ListView::keyPressEvent(QKeyEvent *e)
{
    switch (e->key()) {
        case Qt::Key_Left:
            this->activeTreeBox(this->crtSelBox > 0 ?  --crtSelBox : 0);
            break;
        case Qt::Key_Right:
            this->activeTreeBox(this->crtSelBox < 2 ?  ++crtSelBox : 2);
            break;
        case Qt::Key_Up:
            this->switchTreeListItem(true);
            break;
        case Qt::Key_Down:
            this->switchTreeListItem(false);
            break;
        case Qt::Key_Return:
            if (this->crtSelBox == 2 && this->maskWidget->isHidden()) {
                maskWidget->show();
                this->showSkillPointTree();
            } else if(!this->maskWidget->isHidden()) {
                qDebug() <<  "正常的逻辑代码" << endl;
            }
            break;
        case Qt::Key_Escape:
            if (!this->maskWidget->isHidden()) {
                maskWidget->hide();
                this->popupTree->hide();
            }
            break;
    }
}

void ListView::setOpacity(QWidget &widget, float opactiy)
{
    QGraphicsOpacityEffect *opacityEffect=new QGraphicsOpacityEffect;
    widget.setGraphicsEffect(opacityEffect);
    opacityEffect->setOpacity(opactiy);
}

void ListView::switchTreeListItem(bool isUp)
{

    QList<CustomListItem*> _items;
    CustomListItem *item = NULL;
    if (this->maskWidget->isHidden()) {
        switch (this->crtSelBox) {
            case 0 :
                _items = this->ui->styleItemBox->findChildren<CustomListItem *>();
                break;
            case 1:
                _items = this->ui->actionItemBox->findChildren<CustomListItem *>();
                break;
            case 2:
                _items = this->ui->skillItemBox->findChildren<CustomListItem *>();
                break;
        }
    } else {
        _items = this->popupTreeContent->findChildren<CustomListItem *>();
    }
    for (int i = 0; i < _items.size(); i++) {
        item = _items.at(i);
        if (item->isSelected()) {
            if (isUp && i > 0) {
                item = _items.at(--i);
            } else if(!isUp && i < _items.size() - 1){
                item = _items.at(++i);
            }
            emit item->clicked();
            break;
        }
    }
}

void ListView::showSkillPointTree()
{

    if (this->popupTree == nullptr) {
        this->popupTree = new QWidget();
        // 构建弹窗对象的布局
        QVBoxLayout* mLayout = new QVBoxLayout();
        mLayout->setMargin(0);
        mLayout->setSpacing(0);

        QRect rect = this->ui->skillBox->geometry();
        //获取主控件大小，用于计算弹框的绝对位置
        QRect screenRect = this->geometry();
//        int w = rect.width() + (int)(rect.width()*0.24);
        int w = 900;
        int h = rect.height();
        int x = (screenRect.width() - w)/2;
        int y = rect.y();

        qDebug() << h << this->ui->skillBox->height() << endl;

        // !----------- 头部 ----------
        QGroupBox* header = new QGroupBox();
        QSizePolicy headerPolicy;
        headerPolicy.setHorizontalPolicy(QSizePolicy::Expanding);
        headerPolicy.setVerticalPolicy(QSizePolicy::Fixed);
        header->setSizePolicy(headerPolicy);
        header->setMinimumHeight(80);
        QHBoxLayout* hLayout = new QHBoxLayout();
        hLayout->setContentsMargins(30, 0, 0, 0);
        hLayout->setSpacing(18);


        QLabel* icon = new QLabel();
        QSizePolicy iconPolicy;
        iconPolicy.setHorizontalPolicy(QSizePolicy::Fixed);
        iconPolicy.setVerticalPolicy(QSizePolicy::Fixed);
        icon->setSizePolicy(iconPolicy);
        icon->setMinimumSize(QSize(17, 19));
        icon->setMaximumSize(QSize(17, 19));
        icon->setStyleSheet("border:none;border-image: url(:/res/actions-skill-right-icon.png);");

        QLabel* head = new QLabel();
        head->setText("技术点");
        head->setStyleSheet("color:#71BB3F;border:2px solid #71BB3F;font-size:30px;font-weight:bold;border:none;");
        hLayout->addWidget(icon);
        hLayout->addWidget(head);

        header->setStyleSheet("border:2px solid #71BB3F;border-bottom:none;");
        header->setLayout(hLayout);

        // !-----------  内容 ----------
        popupTreeContent = new QGroupBox();
        QScrollArea* scorll = new QScrollArea();


        QVBoxLayout* vLayout = new QVBoxLayout();
        vLayout->setAlignment(Qt::AlignTop);
        vLayout->setMargin(0);
        vLayout->setSpacing(0);
        vLayout->setContentsMargins(0,30,0,30);


        popupTreeContent->setLayout(vLayout);
        scorll->setWidget(popupTreeContent);
        scorll->setStyleSheet("border:1px solid #71BB3F;");
        scorll->setVerticalScrollBarPolicy(Qt::ScrollBarPolicy::ScrollBarAlwaysOff);
        scorll->setWidgetResizable(true);

        mLayout->addWidget(header);
        mLayout->addWidget(scorll);
        mLayout->setStretch(0, 80);
        mLayout->setStretch(1, 680);
        popupTree->setLayout(mLayout);
        // 设置坐标、样式、提升控件层级
        popupTree->setGeometry(x, y, w, h);
        popupTree->setStyleSheet("background:rgba(0,0,0,1);");
        popupTree->setParent(this);
        popupTree->raise();
    }
    // 清除掉原有的选项
    QList<CustomListItem*> _items = this->popupTreeContent->findChildren<CustomListItem *>();
    CustomListItem* item = nullptr;
    for (int i=0; i < _items.size(); i++) {
        item = _items.at(i);
        delete item;
    }

    // 装载新的数据并展示
    // 模拟N条假数据
    CustomListItem* item1 = new CustomListItem(CustomListItem::ItemStyle::Column, "肘关节运动", "正手攻球");
    CustomListItem* item2 = new CustomListItem(CustomListItem::ItemStyle::Column, "肘关节夹角", "正手攻球");
    CustomListItem* item3 = new CustomListItem(CustomListItem::ItemStyle::Column, "双腿站姿", "正手攻球");
    CustomListItem* item4 = new CustomListItem(CustomListItem::ItemStyle::Column, "大、小腿夹角", "正手攻球");
    CustomListItem* item5 = new CustomListItem(CustomListItem::ItemStyle::Column, "item5", "正手攻球");
    CustomListItem* item6 = new CustomListItem(CustomListItem::ItemStyle::Column, "item6", "正手攻球");
    CustomListItem* item7 = new CustomListItem(CustomListItem::ItemStyle::Column, "item7", "正手攻球");
    CustomListItem* item8 = new CustomListItem(CustomListItem::ItemStyle::Column, "item8", "正手攻球");
    CustomListItem* item9 = new CustomListItem(CustomListItem::ItemStyle::Column, "item9", "正手攻球");
    CustomListItem* item11 = new CustomListItem(CustomListItem::ItemStyle::Column, "item10", "正手攻球");
    CustomListItem* item12 = new CustomListItem(CustomListItem::ItemStyle::Column, "item11", "正手攻球");
    CustomListItem* item13 = new CustomListItem(CustomListItem::ItemStyle::Column, "item12", "正手攻球");
    CustomListItem* item14= new CustomListItem(CustomListItem::ItemStyle::Column, "item13", "正手攻球");

    QVBoxLayout* vLayout = (QVBoxLayout*)this->popupTreeContent->layout();

//    qDebug() << gb->geometry().width() << ":" << gb->geometry().height() << endl;

    vLayout->addWidget(item1);
    vLayout->addWidget(item2);
    vLayout->addWidget(item3);
    vLayout->addWidget(item4);
    vLayout->addWidget(item5);
    vLayout->addWidget(item6);
    vLayout->addWidget(item7);
    vLayout->addWidget(item8);
    vLayout->addWidget(item9);
    vLayout->addWidget(item11);
    vLayout->addWidget(item12);
    vLayout->addWidget(item13);
    vLayout->addWidget(item14);
//    popupTreeContent->setWidget(gb);
//    gb->adjustSize();

    popupTree->show();

    // 触发点击事件
    item1->selected();
}
